<template>
	<jk-dialog
		v-model="showDialog"
		title="点位-趋势分析"
		width="1000px"
		append-to-body
		:show-confirm-btn="false"
		:show-close-btn="true"
		:show-cancel-btn="false"
		@on-close="onVisibleChange(false)"
		@on-visible-change="onVisibleChange"
	>
		<div ref="box1" class="margin-bottom-10">
			<div class="flex-between-center">
				<span>查询条件</span>
				<el-checkbox v-model="isHistory" @change="onHistoryChange">历史记录</el-checkbox>
			</div>
			<jk-card>
				<el-form ref="ruleForm" :model="searchParams" label-width="110px" :show-message="false">
					<el-row ref="box1" class="flex-start-center-wrap">
						<el-col :span="8">
							<el-form-item class="margin-bottom-10" label="机台">
								<jk-select v-model="searchParams.deviceRecordId" :clearable="false" :option-list="machineList" class="width-100-percent" placeholder="络筒" @change="onMachineChange"></jk-select>
							</el-form-item>
						</el-col>
						<el-col :span="8">
							<el-form-item class="margin-bottom-10" label="锭组">
								<jk-select v-model="searchParams.serialNumber" :clearable="false" :option-list="spinGroupList" class="width-100-percent" placeholder="锭组" @change="geChartDataRequest"></jk-select>
							</el-form-item>
						</el-col>
						<el-col :span="8">
							<el-form-item class="margin-bottom-10" label="点位">
								<jk-select v-model="searchParams.typeId" :clearable="false" :option-list="typeList" class="width-100-percent" placeholder="点位" @change="onRadioChange"></jk-select>
							</el-form-item>
						</el-col>
						<el-col v-show="isHistory" :span="8">
							<el-form-item class="margin-bottom-10" label="起始时间">
								<jk-date-picker v-model="searchParams.startDateTime" :clearable="false" type="datetime" :option-list="typeList" class="width-100-percent" placeholder="起始时间" @change="geChartDataRequest"></jk-date-picker>
							</el-form-item>
						</el-col>
						<el-col v-show="isHistory" :span="8">
							<el-form-item class="margin-bottom-10" label="结束时间">
								<jk-date-picker v-model="searchParams.endDateTime" :clearable="false" type="datetime" :option-list="typeList" class="width-100-percent" placeholder="结束时间" @change="geChartDataRequest"></jk-date-picker>
							</el-form-item>
						</el-col>
					</el-row>
				</el-form>
				<div class="flex-center" style="display: flex;flex-direction: column;justify-content: center;align-items: center;">
					<!--<el-radio-group v-model="searchParams.typeId" @change="onRadioChange">
						<el-radio-button v-for="item in typeList" :key="item.id" :label="item.id">{{ item.name }}</el-radio-button>
					</el-radio-group>-->
					<el-button :loading="showLoading" size="small" icon="el-icon-refresh" type="primary" @click="onRefreshBtn">查询</el-button>
				</div>
			</jk-card>
		</div>
		<div class="lt-params-chart-container" :style="{ height: `${dialogTableHeight - 20}px`, background: '#f8f8f9', borderRadius: '6px' }">
			<div ref="ltSpinGroupParamsChart" v-resize="resizeChart" style="width: 100%;height: 100%;"></div>
		</div>
	</jk-dialog>
</template>

<script>
    import calHeight from '/src/mixins/cal-dialog-height';
    import {
        borderColor,
        color,
        legendTextStyle
    } from './components/chart-conf';
    import * as echarts from 'echarts';
    import domResizeMixin from '../../../mixins/dom-resize';
    import { iotCollectDataLtCutSignalInfo } from '../../../api/production/xsReport';
    import { machinemanagerMachineGet, machinemanagerMachinePage } from '../../../api/machine/machineArchives';
    import { filZero, formatTime } from '../../../utils/jk/jk-tool';
    import ltParams from './lt-params';
    export default {
        mixins: [domResizeMixin, calHeight, ltParams],
        components: {},
        props: {
            chartParams: {
                type: Object,
                default() {
                    return {};
                }
            },
            dialogState: {
                type: Boolean,
                default: false
            },
            dataId: {
                type: [String, Number],
                default: ''
            }
        },
        data() {
            return {
                timer: {},
                machineList: [],
                searchParams: {
                    resourceType: 1, // 洛菲
                    deviceRecordId: null,
                    startDateTime: '',
                    endDateTime: '',
                    typeId: 1,
                    signalName: null,
                    scheduleShiftId: null,
                    serialNumber: null
                },
                spinGroupList: [],
                option: {
                    title: {
                        text: '',
                        textStyle: {
                            fontWeight: 'none'
                        }
                    },
                    grid: {
                        top: '30px',
                        right: '10px',
                        bottom: '10px',
                        left: '20px',
                        containLabel: true
                    },
                    legend: {
                        data: [],
                        textStyle: {
                            color: legendTextStyle
                        }
                    },
                    xAxis: {
                        type: 'category',
                        data: [],
                        axisLabel: {
                            show: true,
                            color: color

                        },
                        nameTextStyle: {
                            color: 'red'
                        },
                        boundaryGap: true,
                        axisLine: {
                            lineStyle: {
                                color: borderColor
                            }
                        }
                    },
                    yAxis: [
                        {
                            type: 'value',
                            // max: 400,
                            splitLine: {
                                lineStyle: {
                                    color: 'none'
                                }
                            },
                            axisLabel: {
                                show: true,
                                color: color

                            },
                            axisLine: {
                                lineStyle: {
                                    color: borderColor
                                }
                            }
                        }
                    ],
                    series: [
                        {
                            name: '',
                            type: 'line',
                            data: [],
                            smooth: false,
                            barGap: 0,
                            symbol: 'none',
                            itemStyle: {
                                color: '#2378f7'
                            }
                        }
                    ]
                },
                chartData: [],
                tableLoading: false,
                tableData: [],
                showDialog: false,
                showLoading: true,
                isHistory: false
            };
        },
        methods: {
            clearTimeV() {
                clearInterval(this.timer);
            },
            onHistoryChange(e) {
                this.clearTimeV();
                if (!e) {
                    this.$set(this.searchParams, 'endDateTime', '');
                    this.run();
                }
                this.calDialogViewHeight();
            },
            setStartDateTime() {
                this.$set(this.searchParams, 'startDateTime', formatTime(Date.now() - (12 * 60 * 60 * 1000)));
            },
            run() {
                if (this.searchParams.deviceRecordId && this.searchParams.serialNumber && this.searchParams.startDateTime && this.searchParams.typeId) {
                    this.clearTimeV();
                    this.timer = setInterval(() => {
                        this.setStartDateTime();
                        this.geChartDataRequest();
                    }, 8000);
                }
            },
            onRefreshBtn() {
                this.geChartDataRequest();
            },
            onRadioChange() {
                this.geChartDataRequest();
            },
            onMachineChange() {
                this.chartData = [];
                this.$set(this.searchParams, 'serialNumber', null);
                this.updateChart();
                this.getMachineDetailRequest();
            },
            onVisibleChange(e) {
                this.$emit('on-visible-change', e);
                if (!e) {
                    this.clearTimeV();
                    Object.assign(this.$data, this.$options.data());
                }
            },
            formatTimeCode(e) {
                const d = new Date(e);
                const month = filZero(d.getMonth() + 1);
                const day = filZero(d.getDate());
                const hours = filZero(d.getHours());
                const minutes = filZero(d.getMinutes());
                const seconds = filZero(d.getSeconds());
                return `${month}/${day} ${hours}:${minutes}:${seconds}`;
            },
            geChartDataRequest() {
                if (this.searchParams.deviceRecordId && this.searchParams.serialNumber && this.searchParams.startDateTime && this.searchParams.typeId) {
                    const params = JSON.parse(JSON.stringify(this.searchParams));
                    const signalItem = this.typeList.find(x => x.id === params.typeId) || {};
                    params.signalName = signalItem.alias;
                    delete params.typeId;
                    this.showLoading = true;
                    return iotCollectDataLtCutSignalInfo(params).then(res => {
                        this.showLoading = false;
                        if (res.data.status === 200) {
                            this.chartData = res.data.res.map(x => {
                                x.dateTime = this.formatTimeCode(x.collectTime);
                                return x;
                            });
                            this.updateChart();
                        }
                    });
                }
            },
            resize() {
                window.addEventListener('resize', () => {
                    this.resizeChart();
                });
            },
            initChart() {
                this.$nextTick(() => {
                    this.example = echarts.init(this.$refs.ltSpinGroupParamsChart);
                    this.example.setOption(this.option);
                });
            },
            updateChart() {
                if (this.example) {
                    this.$nextTick(() => {
                        const signalItem = this.typeList.find(x => x.id === this.searchParams.typeId) || {};
                        this.option.legend.data = [signalItem.name];
                        this.option.xAxis.data = this.chartData.map(x => x.dateTime);
                        this.option.series[0].data = this.chartData.map(x => x.value);
                        this.option.series[0].name = signalItem.name;
                        const arr = this.chartData;
                        this.option.tooltip = {
                            trigger: 'axis',
                            formatter(params) {
                                let str = '';
                                str += `<div style="display: flex; align-items: center;">${params[0].axisValueLabel}</div>`;
                                str += `<div style="display: flex; align-items: center;"><div style="width: 10px;height: 10px;border-radius: 50%;background: #2378f7;margin-right: 4px;"></div><span>${params[0].seriesName}: ${params[0].value} </span></div>`;
                                str += `<div style="display: flex; align-items: center;"><div style="width: 10px;height: 10px;border-radius: 50%;background: none;margin-right: 4px;"></div><span>规格+批号+机台: ${arr[params[0].dataIndex].batchCode} </span></div>`;
                                str += `<div style="display: flex; align-items: center;"><div style="width: 10px;height: 10px;border-radius: 50%;background: none;margin-right: 4px;"></div><span>细纱支数: ${arr[params[0].dataIndex].yarnCount} </span></div>`;
                                return str;
                            }
                        };
                        this.example.setOption(this.option);
                    });
                } else {
                    this.initChart();
                }
            },
            getLtListRequest() {
                return machinemanagerMachinePage({
                    auditState: 1,
                    processCode: 'LT'
                }).then(res => {
                    if (res.data.status === 200) {
                        this.machineList = res.data.res;
                    }
                });
            },
            getMachineDetailRequest() {
                if (this.searchParams.deviceRecordId) {
                    return machinemanagerMachineGet({ id: this.searchParams.deviceRecordId }).then(res => {
                        if (res.data.status === 200) {
                            this.spinGroupList = res.data.res.spinGroupList ? res.data.res.spinGroupList.map(x => {
                                return {
                                    id: x.sortNum,
                                    name: `${x.startSpinNumber}~${x.endSpinNumber}`
                                };
                            }) : [];
                        }
                    });
                }
            },
            async getDependentData() {
                this.showLoading = true;
                await this.getLtListRequest();
                if (this.searchParams.deviceRecordId) await this.getMachineDetailRequest();
                await this.geChartDataRequest();
                this.run();
                this.showLoading = false;
            }
        },
        mounted() {
        },
        watch: {
            dialogState(newVal) {
                this.showDialog = newVal;
                if (newVal) {
                    this.$set(this.searchParams, 'deviceRecordId', this.chartParams.machineId);
                    this.$set(this.searchParams, 'serialNumber', this.chartParams.sortNum);
                    this.$set(this.searchParams, 'typeId', this.typeList.find(x => x.alias === this.chartParams.signalName).id);
                    this.$set(this.searchParams, 'signalName', this.chartParams.signalName);
                    this.setStartDateTime();
                    this.resize();
                    this.initChart();
                    this.getDependentData();
                }
            }
        }
    };
</script>
<style scoped lang="scss">
    .lt-params-chart-container {
        padding: 12px;
    }
</style>
